package com.zh.plus;

import com.zh.util.BeanValidators;
import com.zh.util.dict.CodeMsg;
import com.zh.vo.Result;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

    /**
     * 这个是参数校验的功能的
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        List<String> list = BeanValidators.extractMessage(ex);
        return new Result(CodeMsg.BIND_ERROR.getCode(),"参数验证失败：" + list.get(0));
    }

/*
    如果在此外拦截Exception,这样logger日志没有完整的error日志，所以暂时采用MyErrorController的办法先用着。用时间再解决这个问题
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result eee(Exception ex) {
       // logger.error(ex.p);
        //ex.printStackTrace();
        logger.error(ex..getStackTrace());
        return Result.failure(CodeMsg.SERVER_ERROR);
    }*/

}